﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.ModelConfiguration;

namespace cs499.Database
{
    public partial class Place
    {
        public override string ToString() {
            return PlaceName;
        }

        public bool Delete()
        {
            bool retval=true;
            Model1Container db = new Model1Container();
            Place place = db.Set<Place>()
                .Include("DependentCourses")
                .FirstOrDefault(placetofind => placetofind.PlaceName == this.PlaceName && placetofind.Id == this.Id);
            if (place != null)
            {
                foreach (Course cr in place.DependentCourses)
                {
                    retval = retval && cr.PlaceRequirements.Remove(place);
                    cr.PlaceRequirementsstring = cr.PlaceRequirements.PlaceListToString();
                }
                if (place is Building)
                {
                    retval = retval && ((Building)place).DeleteRooms();
                }
                else if(place is Room)
                {
                    foreach (CourseInstance ci in db.Set<Room>().Include("CourseInstances").FirstOrDefault(rm => rm.Id == place.Id).CourseInstances.ToList())
                    {
                        db.Set<CourseInstance>().Remove(ci);
                    }
                }
                try
                {
                    db.Set<Place>().Remove(place);
                    db.SaveChanges();
                }
                catch (Exception /**/) {
                    return false;
                }
            }
            return retval;
        }
    }

    public static class PlaceExtension
    {
        public static string PlaceListToString(this ICollection<Place> myList, string delimiter = ", ")
        {
            System.Text.StringBuilder outstr = new System.Text.StringBuilder();
            foreach (Place place in myList)
            {
                outstr.Append(place.ToString() + delimiter);
            }
            
            if (outstr.Length == 0) return "";
            outstr.Remove((outstr.Length) - delimiter.Length, delimiter.Length);
            return outstr.ToString();
        }

        public static string PlacesToString(ICollection<Place> myList, string delimiter=", ")
        {
            return PlaceExtension.PlaceListToString(myList,delimiter);
        }
    }
}